package org.hepeng.workx.spring.cloud.netflix.ribbon.loadbalancer;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.hepeng.workx.spring.cloud.netflix.ribbon.RibbonRequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * @author he peng
 */
public class ServerPortRule extends AbstractThreadIsolationRule {

    private static final Logger LOG = LoggerFactory.getLogger(ServerPortRule.class);

    public ServerPortRule() {}

    public ServerPortRule(String serverPortParamName) {
        super(serverPortParamName);
    }

    public ServerPortRule(String paramName, IRule rule) {
        super(paramName, rule);
    }

    @Override
    public List<Server> getParticipateLoadBalancingServers(Object key, RibbonRequestContext ribbonContext, List<Server> originalAllServers) {
        LOG.info("{} rules works" , ServerPortRule.class.getName());

        List<Server> loadBalancingServers = new ArrayList<>();
        String decideLoadBalanceParam = getDecideLoadBalanceParam(ribbonContext);
        int paramServerPort = StringUtils.isNotBlank(decideLoadBalanceParam) && NumberUtils.isDigits(decideLoadBalanceParam)
                ? Integer.valueOf(decideLoadBalanceParam) : -1;

        LOG.info("The specified routing server port is {} " , decideLoadBalanceParam);
        for (Server server : originalAllServers) {
            int serverPort = server.getPort();
            if (paramServerPort == serverPort) {
                LOG.info("Matched server {} " , server);
                loadBalancingServers.add(server);
            }
        }
        return loadBalancingServers;
    }
}
